﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using HouseSecretary.Base;
using HouseSecretary.Common.DEncrypt;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Net;
using System.Diagnostics;

namespace HouseSecretary
{
    public partial class LoginForm : HouseSecretary.Base.DlgForm
    {
         
        private int loginTimes = 0;
        /// <summary>
        /// 当前保存的连接字符串
        /// </summary>
        public string InitConnString = "";
        public LoginForm()
            : base(false)
        {
            InitializeComponent();

        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            this.Text += "(版本" + Base.GlobalParams.GLOBAL_VERSION + ")";
            txtLoginID.Text = Common.ConfigHelper.GetConfigString("LastLogid");
           
        }
       
        private void btnLogin_Click(object sender, EventArgs e)
        {
            JObject jObject = new JObject();
            jObject["method"] = "DBConnectTest";
            jObject["msg"] = "";
            string jsonMsg = Base.GlobalParams.HttpWebClientObj.GetReturnData(jObject);

            string code = "";
            string msg = "";
            Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);


            if (code != "0")
            {
                XtraMessageBox.Show(msg, "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                string logid = txtLoginID.Text.Trim();
                if (logid == "")
                {
                    XtraMessageBox.Show("用户名不能为空。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                string password = txtPassword.Text.Trim();
                string userName = "";

#if DEBUG

                string loginString = "{'logid':'" + logid + "','password':'" + password + "','mode':'DEBUG'}";

                loginString = DESEncrypt.Encrypt(loginString, Base.GlobalParams.GLOBAL_ENCRYPTVALUE);
                jObject = new JObject();
                jObject["method"] = "Login";
                jObject["msg"] = loginString;
                jsonMsg = Base.GlobalParams.HttpWebClientObj.GetReturnData(jObject);

                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                if (code != "0")
                {
                    XtraMessageBox.Show(msg, "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                     JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                     userName = msgObj["FUserName"].ToString();
                }

#else
                
                string loginString = "{'logid':'" + logid + "','password':'" + password + "'}";

                loginString = DESEncrypt.Encrypt(loginString, Base.GlobalParams.GLOBAL_ENCRYPTVALUE);

                jObject = new JObject();
                jObject["method"] = "Login";
                jObject["msg"] = loginString;
                jsonMsg = Base.GlobalParams.HttpWebClientObj.GetReturnData(jObject);
                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                if (code != "0")
                {
                    loginTimes++;
                   
                    if (loginTimes == 3)
                    {
                        XtraMessageBox.Show(msg+"，系统将退出。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.DialogResult = DialogResult.Cancel;
                Thread.Sleep(5000);
            Application.Exit();
            
                    }
                    else
                    {
                        int leftLoginTimes = 3 - loginTimes;
                        XtraMessageBox.Show(msg+"，您还有" + leftLoginTimes.ToString() + "次尝试机会。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        
                    }
                    return;
                }
                else
                {
                     JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                     userName = msgObj["FUserName"].ToString();
                }
#endif


#if DEBUG

#else

               // 判断用户是否需要升级

                jObject = new JObject();
                jObject["method"] = "GetFAppVer";
                jObject["msg"] = "";
                jsonMsg = Base.GlobalParams.HttpWebClientObj.GetReturnData(jObject);

                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                if (code != "0")
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                    string FAppVer = msgObj["FAppVer"].ToString();
                    decimal newVersion = 0;
                    if (!decimal.TryParse(FAppVer, out newVersion))
                    {
                        XtraMessageBox.Show("系统异常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    decimal appVersion = decimal.Parse(Base.GlobalParams.GLOBAL_VERSION);
                    if (appVersion < newVersion)
                    {
                        this.DialogResult = DialogResult.Cancel;
                        System.Diagnostics.Process.Start(AppDomain.CurrentDomain.BaseDirectory.ToString() + "update.exe");
                        return;
                    }
                   
                }
               
#endif

                //将本次登录名写入到config文件中
                Common.ConfigHelper.SeTconfigKeyValue("LastLogid", logid);

                // 记录用户当前的版本信息和IP地址
                //string ipaddr = Common.GlobalUtil.GetLocalIP();
                //prvUserBLL.UpdateLoginInfo(logid, Base.GlobalParams.GLOBAL_VERSION, ipaddr);


                Base.GlobalParams.GLOBAL_LOGID = logid;
                Base.GlobalParams.GLOBAL_LOGFULLNAME = userName;
                //Base.GlobalParams.GLOBAL_IPADDRESS = ipaddr;
                Base.GlobalParams.GLOBAL_COMPUTENAME = Common.GlobalUtil.GetLocalComputeName();

                DateTime EndDatetime = DateTime.Now;

                jObject = new JObject();
                jObject["method"] = "GetServerDatetime";
                jObject["msg"] = "";
                jsonMsg = Base.GlobalParams.HttpWebClientObj.GetReturnData(jObject);

                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                if (code == "0")
                {
                    JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                    EndDatetime = DateTime.Parse(msgObj["ServerDatetime"].ToString());
                }

                //同步本地时间和服务器时间
                //Common.ImportDllApiUtil.str_SystemTime sysTimeStruct = new Common.ImportDllApiUtil.str_SystemTime();
                //sysTimeStruct.wYear = (ushort)EndDatetime.Year;
                //sysTimeStruct.wMonth = (ushort)EndDatetime.Month;
                //sysTimeStruct.wDayOfWeek = (ushort)EndDatetime.DayOfWeek;
                //sysTimeStruct.wDay = (ushort)EndDatetime.Day;
                //sysTimeStruct.wHour = (ushort)EndDatetime.Hour;
                //sysTimeStruct.wMinute = (ushort)EndDatetime.Minute;
                //sysTimeStruct.wSecond = (ushort)EndDatetime.Second;
                //sysTimeStruct.wMiliseconds = (ushort)EndDatetime.Millisecond;
                //Common.ImportDllApiUtil.SetLocalTime(ref sysTimeStruct);

                

                ////登录成功后写日志
                //string localComputeLoginName = Common.GlobalUtil.GetLoalComputeLoginName();
                //Model.Apslogrec apslogrecModel = new Model.Apslogrec();
                //apslogrecModel.start_time = StartDatetime;
                //apslogrecModel.over_time = EndDatetime;

                //apslogrecModel.logname = Base.GlobalParams.GLOBAL_LOGFULLNAME;
                //apslogrecModel.ip_addr = Base.GlobalParams.GLOBAL_IPADDRESS;
                //apslogrecModel.computername = Base.GlobalParams.GLOBAL_COMPUTENAME;
                //apslogrecModel.Operator = "登录 NT User: " + localComputeLoginName + " from " + apslogrecModel.computername;
                //apslogrecModel.FEntityNo = Base.GlobalParams.GLOBAL_ENTITY_NO;
                //sysSettingBLL.AddLog(apslogrecModel);
                
                this.DialogResult = DialogResult.OK;

            }

            

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }

        /// <summary>
        /// 鼠标离开 注册账号 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblRegister_MouseLeave(object sender, EventArgs e)
        {
            lblRegister.ForeColor = Color.FromArgb(65, 149, 231);
        }

        /// <summary>
        /// 鼠标移上 注册账号 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblRegister_MouseEnter(object sender, EventArgs e)
        {
            lblRegister.ForeColor = Color.FromArgb(71, 210, 241);
        }
        /// <summary>
        /// 注册账号链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblRegister_Click(object sender, EventArgs e)
        {
            string url = "http://www.baidu.com";
            try
            {
                Process.Start(url);
            }
            catch
            {
                XtraMessageBox.Show("打开网页错误，请手动打开以下链接：" + url, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 鼠标移上 找回密码 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblFindPwd_MouseEnter(object sender, EventArgs e)
        {
            lblFindPwd.ForeColor = Color.FromArgb(71, 210, 241);
        }
        /// <summary>
        /// 鼠标离开 找回密码 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblFindPwd_MouseLeave(object sender, EventArgs e)
        {
            lblFindPwd.ForeColor = Color.FromArgb(65, 149, 231);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblFindPwd_Click(object sender, EventArgs e)
        {
            string url = "http://www.baidu.com";
            try
            {
                Process.Start(url);
            }
            catch
            {
                XtraMessageBox.Show("打开网页错误，请手动打开以下链接："+url, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        

       

    }
}
